import { combineReducers } from 'redux'
import { ADD_TODO, TOGGLE_TODO, SET_VISIBILITY_FILTER, VisibilityFilters } from './action';

// 1. 设计 state
/*
const initialState = {
    visibilityFilter: VisibilityFilters.SHOW_ALL,
    todos: [
        {
            text: 'xxx',
            completed: false
        },
        {
            ...
        }
    ]
};
*/

// 2. 根据 state 结构, 编写子 reducer

const { SHOW_ALL } = VisibilityFilters; // 对象的解构赋值

// reducer
// visibilityFilter 默认为 SHOW_ALL
function visibilityFilter(state = SHOW_ALL, action) {
    console.log('调用了 visibilityFilter reducer.');
    // 调用 visibilityFilter reducer 时, action 中应该是 { type: SET_VISIBILITY_FILTER, filter: xxx }
    switch (action.type) {
        case SET_VISIBILITY_FILTER:
            // state 中的 visibilityFilter 部分, 用 action.filter 代替.
            return action.filter;
        default:
            return state;
    }
}

// reducer
// todos 默认为空数组
function todos(state = [], action) {
    console.log('调用了 todos reducer.');
    switch (action.type) {
        // 如果是 ADD_TODO, 就添加一项到原 todos 中.
        case ADD_TODO:
            return [
                ...state,
                {
                    text: action.text,
                    completed: false
                }
            ];
        // 如果是切换, 那就用 map 计算需要切换的那一项, 并返回新的 todos 数组.
        case TOGGLE_TODO:
            return state.map((todo, index) => {
                if (index === action.index) {
                    return Object.assign({}, todo, {
                        completed: !todo.completed
                    });
                }
                return todo;
            });
        default:
            return state;
    }
}

// 3. 合并子 reducer
const todoApp = combineReducers({
    visibilityFilter,
    todos
});

// 4. 暴露 root reducer
export default todoApp